"""
代理IP工具模块
"""
import logging
import random
import requests
import time

logger = logging.getLogger(__name__)

# 示例代理IP列表（实际使用时应该从代理服务商获取或从文件读取）
PROXY_LIST = [
    # 格式: "协议://用户名:密码@IP:端口" 或 "协议://IP:端口"
    # "http://127.0.0.1:7890",
    # "https://127.0.0.1:7890",
]


class ProxyManager:
    """代理IP管理器"""
    
    def __init__(self, proxy_list=None):
        self.proxy_list = proxy_list or PROXY_LIST
        self.current_proxy = None
        self.failed_proxies = set()
    
    def get_random_proxy(self):
        """获取随机代理IP"""
        available_proxies = [p for p in self.proxy_list if p not in self.failed_proxies]
        if not available_proxies:
            logger.warning("没有可用的代理IP")
            return None
        
        self.current_proxy = random.choice(available_proxies)
        return self.current_proxy
    
    def mark_proxy_failed(self, proxy=None):
        """标记代理IP失败"""
        if proxy is None:
            proxy = self.current_proxy
        
        if proxy and proxy in self.proxy_list:
            logger.info(f"标记代理失败: {proxy}")
            self.failed_proxies.add(proxy)
    
    def get_proxy_dict(self, proxy=None):
        """获取代理字典，用于requests库"""
        if proxy is None:
            proxy = self.current_proxy or self.get_random_proxy()
        
        if not proxy:
            return {}
        
        return {
            "http": proxy if proxy.startswith("http://") else f"http://{proxy}",
            "https": proxy if proxy.startswith("https://") else f"https://{proxy}",
        }
    
    def test_proxy(self, proxy=None, test_url="https://www.baidu.com", timeout=5):
        """测试代理是否可用"""
        if proxy is None:
            proxy = self.current_proxy or self.get_random_proxy()
        
        if not proxy:
            return False
        
        try:
            proxy_dict = self.get_proxy_dict(proxy)
            start_time = time.time()
            response = requests.get(test_url, proxies=proxy_dict, timeout=timeout)
            elapsed = time.time() - start_time
            
            if response.status_code == 200:
                logger.info(f"代理 {proxy} 可用，响应时间: {elapsed:.2f}秒")
                return True
            else:
                logger.warning(f"代理 {proxy} 返回状态码: {response.status_code}")
                return False
        except Exception as e:
            logger.warning(f"代理 {proxy} 测试失败: {str(e)}")
            return False 